package org.wenhuayuan.project.common.tab;

import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.wenhuayuan.uilibrary.tab.bottom.HiTabBottomInfo;

import java.util.List;

public class HiTabViewAdapter {
    private List<HiTabBottomInfo<?>> infoList;
    private Fragment curFragment;
    private FragmentManager fragmentManager;

    public HiTabViewAdapter(FragmentManager fragmentManager, List<HiTabBottomInfo<?>> infoList) {
        this.infoList = infoList;
        this.fragmentManager = fragmentManager;
    }

    /**
     * 实例化及显示pos位置的fragment
     * @param container
     * @param pos
     */
    public void instantiateItem(View container, int pos) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (curFragment != null) {
            fragmentTransaction.hide(curFragment);
        }
        String name = container.getId() + ":" + pos;
        Fragment fragment = fragmentManager.findFragmentByTag(name);
        if (null != fragment) {
            fragmentTransaction.show(fragment);
        } else {
            fragment = getFragmentItem(pos);
            if(!fragment.isAdded()) {
                fragmentTransaction.add(container.getId(), fragment, name);
            }
        }
        curFragment = fragment;
        fragmentTransaction.commitNowAllowingStateLoss();
    }

    // 通过HiTabBottomInfo中的Fragment创建实例
    private Fragment getFragmentItem(int position) {
        try {
            return infoList.get(position).fragment.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getCount() {
       return null != infoList ? infoList.size() : 0;
    }

    public List<HiTabBottomInfo<?>> getInfoList() {
        return infoList;
    }

    public Fragment getCurFragment() {
        return curFragment;
    }
}
